//原来的 把图片画在Canvas上，以及种子画框、数量修改、弹出菜单等操作
//由点击事件来设置种子的新属性
function setSeedLabel(newLabel, ii) {
	if (!window.g_data) {
		console.log('没有数据');
		return;
	}

	let boxes = window.g_data.boxes;
	let box = boxes[ii];
	let oldLabel = box[0];

	if (oldLabel == newLabel) {
		bootbox.alert({
			title: "提示",
			message: "种子检测结果没有改!",
			size: 'small'
		});
		return;
	}

	box[0] = newLabel;
	let arr = getInputDataArray();

	arr[oldLabel] = arr[oldLabel] - 1; //原标签减1,不影响最后arr[3]的值
	if (newLabel == 3) {
		//window.g_data.boxes.splice(ii, 1); //OK：去掉这个box
		//不需要做任何操作，box[0]=3，就是新识别成删除的种子
	} else {
		arr[newLabel] = arr[newLabel] + 1; //新标签加1
	}

	arr[3] = arr[0] + arr[1];

	setData(arr, '', false); //不替换

	setTimeout(showBoxesInCanvas, 100);

	document.querySelector("#boxesDiv").focus();
}

//清掉显示的box
function removeBoxes() {
	const $canvasImg = document.querySelector("#show");
	const $canvas = document.querySelector("#showBox");
	let ctx = $canvas.getContext("2d");
	ctx.clearRect(0, 0, $canvas.width, $canvas.height);
	ctx.clearRect(0, 0, $canvasImg.width, $canvasImg.height);

	console.log('removeBoxes')
	removeCurrentDiv(); //清掉弹出的菜单
}

//在canvas上绘制boxes的调用
function showBoxesInCanvas() {
	//console.log('showBoxesInCanvas.........');
	if (!window.g_data) {
		alert('没有数据');
		return;
	}
	removeCurrentDiv();

	const $canvasImg = document.querySelector("#show");

	const $canvas = document.querySelector("#showBox");
	let ctx = $canvas.getContext("2d");
	ctx.clearRect(0, 0, $canvas.width, $canvas.height);
	ctx.clearRect(0, 0, $canvasImg.width, $canvasImg.height);

	var rects = g_data.boxes;
	drawBoxes(ctx, 0, rects); //画出label=0的种子
	drawBoxes(ctx, 1, rects); //画出label=1的种子
	drawBoxes(ctx, 2, rects); //画出label=2的种子

	drawBoxes(ctx, 3, rects); //画出label=3的种子，被删除的种子

	if (document.querySelector("#labelNumber").checked == true)
		labelSeedNumbers(ctx);
}

//在canvas上显示div以及 绑定弹出菜单
function doShowDiv(evt) {
	//console.log('doShowDiv.....');
	if (!window.g_data) {
		console.log('没有数据');
		return;
	}
	const $canvas = document.querySelector("#showBox");
	var rect = $canvas.getBoundingClientRect();

	if (isMobileDevice(true) == true) {
		var clientXX = evt.originalEvent.touches[0].clientX; //evt.changedTouches[0].clientX;
		var clientYY = evt.originalEvent.touches[0].clientY; //evt.changedTouches[0].clientY;
	} else {
		var clientXX = evt.clientX;
		var clientYY = evt.clientY;
	}

	x = (clientXX - rect.left) * ($canvas.width / rect.width);
	y = (clientYY - rect.top) * ($canvas.height / rect.height);

	//console.log('x=', x, '\ty=', y);
	//console.log('xxx=', evt.clientX - rect.left, '\tyyy=', evt.clientY - rect.top);

	var rects = g_data.boxes;
	let ratioX = rect.width / $canvas.width;
	let ratioY = rect.height / $canvas.height;

	for (let i in rects) {
		let box = rects[i]
		if (x <= box[4] && x >= box[2] && y <= box[5] && y >= box[3]) {
			if (window.saveDiv) {
				let ii = window.saveDiv.getAttribute('my_index');
				if (ii == i)
					return; //说明还在显示中
			}
			showSeedMaskDiv(box, ratioX, ratioY, i, $canvas);

			return;
		}
	}
	console.log('no click.........');
}
//在canvas上显示半透明层，提供下拉菜单的弹出
function showSeedMaskDiv(box, ratioX, ratioY, ii, $canvas) {
	console.log('showSeedMaskDiv.....');
	let colors = ['red', 'blue', 'black'];
	let div = document.createElement('a');

	let ww = 3;
	let dd = 1;
	if (window.devicePixelRatio) //返回设备的DPR
		dd = window.devicePixelRatio;

	div.style.left = (box[2] * ratioX - ww) + "px";
	div.style.top = (box[3] * ratioY - ww) + "px";
	div.style.width = ((box[4] - box[2] + 1) * ratioX + ww) + "px";
	div.style.height = ((box[5] - box[3] + 1) * ratioY + ww) + "px";

	//console.log('showSeedMaskDiv___x=', div.style.left, '\ty=', div.style.top,
	//      '\twidth=', div.style.width, '\theight=', div.style.height);

	div.className = 'floatBox';
	div.style.borderColor = colors[box[0]];
	div.setAttribute('data-toggle', 'dropdown');
	div.setAttribute('my_index', ii);
	div.setAttribute('my_label', box[0]);

	$($canvas.parentNode).find('a[data-toggle]').remove(); //删除全部a

	div.onclick = function() {
		window.saveDiv = this;
		console.log('....in div.onclick');
	};
	$canvas.parentNode.appendChild(div);
}

function removeCurrentDiv() { //删除当前激活的mask
	if (window.saveDiv) {
		$(window.saveDiv).remove(); //最后删除					
	}
	window.saveDiv = null;
}

//查询是PC端还是移动端
function isMobileDevice(bShow) {
	var sUserAgent = navigator.userAgent.toLowerCase();
	var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
	var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
	var bIsMidp = sUserAgent.match(/midp/i) == "midp";
	var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
	var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
	var bIsAndroid = sUserAgent.match(/android/i) == "android";
	var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
	var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
	if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
		if (bShow == true)
			console.log('移动端');
		return true; // 移动设备
	} else {
		if (bShow == true)
			console.log('PC端');
		return false; // PC
	}
}

//画出 矩形框
function drawBoxes(ctx, label, rects) {
	let colors = ['red', 'blue', 'yellow', '#999999'];

	ctx.beginPath();
	ctx.lineWidth = "3";
	ctx.strokeStyle = colors[label];

	for (let box of rects) {
		if (box[0] == label)
			ctx.rect(box[2], box[3], box[4] - box[2], box[5] - box[3]);
	}
	ctx.stroke();
}

function labelSeedNumbers(ctx) {
	//console.log('labelSeedNumbers........')
	if (!window.g_data) {
		console.log('没有数据');
		return;
	}
	if (!window.g_data.sorted) {
		window.g_data.boxes.sort(function(a, b) {
			if (a[2] != b[2]) return a[3] - b[3];
			else return a[2] - b[2];
		});
		console.log('排序成功...')
		window.g_data.sorted = true;
	}

	var rects = g_data.boxes;

	ctx.font = "47px Times New Romans";
	ctx.fillStyle = 'blue';

	for (let i in rects) {
		box = rects[i];
		let dd = box[4] - box[2]
		ctx.fillText(String(Number(i) + 1), box[2], box[3] - 10)
	}
}
//////////////////////////////////////////////////////////////////
//主要是页面交互的代码
function copyToClipboard() {
	let main = document.querySelector("#result");
	let health = main.querySelector("#health").value;
	let oneleaf = main.querySelector("#oneleaf").value;
	let partial = main.querySelector("#partial").value;
	let seeds = main.querySelector("#seeds").value;
	let oInput = main.querySelector("#copy_data");

	let res = '发芽种子检测数量：' + health;
	//res += '\n单叶种子数量：' + oneleaf;
	//res += '\n不确定种子数量：' + partial;
	oInput.value = res;

	oInput.select(); //选择对象
	document.execCommand("Copy"); //执行浏览器复制命令
	bootbox.alert({
		title: "提示",
		message: "复制成功！",
		size: 'small'
	});
}

function handleTakePhoto(e) {
	let arr = [0, 0, 0, 0];
	setData(arr, '', true);

	// 读取照片
	if (this.files && this.files[0]) {
		const fileData = this.files[0],
			fileReader = new FileReader();
		// 转化为base64
		fileReader.readAsDataURL(fileData);

		fileReader.onload = (e) => {
			changePhotoSize(fileReader.result).catch(e => {})
		};
	}
}

//准备再canvas中调用绘图
function changePhotoSize(imgData) {
	const $canvas = document.querySelector("#show"),
		context = $canvas.getContext("2d"),
		image = new Image();

	image.src = imgData;
	$('#spinner').show(); //显示进度条

	let $canvasBox = document.querySelector("#showBox");

	return new Promise((resolve, reject) => {
		console.log('2222222');
		image.onload = function() {
			let divWidth = document.querySelector('#main').offsetWidth;

			$canvas.setAttribute("width", this.width + "px");
			$canvas.setAttribute("height", this.height + "px");

			$canvasBox.setAttribute("width", this.width + "px");
			$canvasBox.setAttribute("height", this.height + "px");

			let ctx = $canvasBox.getContext("2d");

			ctx.clearRect(0, 0, this.width, this.height);
			context.drawImage(this, 0, 0, this.width, this.height);

			resolve($canvas.toDataURL());

			$('#spinner').hide();
			//window.imgSize = [this.width, this.height];
			console.log(this.width, this.height);
		};
		image.onerror = (e) => {
			reject(e);
		};
	});
}

//提取4个输入框的数据
function getInputDataArray() {
	let arr = new Array(4);
	let $div = document.querySelector('#result');
	arr[0] = Number($div.querySelector('#health').value);
	arr[1] = Number($div.querySelector('#oneleaf').value);
	arr[2] = Number($div.querySelector('#partial').value);
	arr[3] = Number($div.querySelector('#seeds').value);
	return arr;
}

function showData(data) {
	let arr = [Number(data.stat.health), Number(data.stat.oneleaf),
		Number(data.stat.partial), Number(data.stat.seeds)
	];

	$("#result div.input-group span.font-weight-bold").each(function(index, dom) {//右侧的返回的检测结果
		dom.innerText = arr[index];
	});
	
	if (data.changeNum) {
		arr = [Number(data.changeNum.health), Number(data.changeNum.oneleaf),
			Number(data.changeNum.partial), Number(data.changeNum.seeds)
		];//增加保存数据的读入并兼容原来的程序
	}
	
	setData(arr, data.fileImageWebPath, false);

	document.querySelector('#msgResult').innerText = data.statusText;
	document.querySelector('#file_detect_name').innerText = data.fileName;
}
//设置输入框的数字显示
function setData(arr, href, replaceImg) {
	let $div = document.querySelector('#result');

	$div.querySelector('#health').value = arr[0];
	$div.querySelector('#oneleaf').value = arr[1];
	$div.querySelector('#partial').value = arr[2];
	$div.querySelector('#seeds').value = arr[3];

	if (replaceImg == true)
		if ($div.querySelector('#showImg').style.display != 'none')
			$div.querySelector('#showImg').src = href;

	$jqs = $("#result input[inputmode='decimal']");
	$jqs.each(function(index, dom) {
		$(dom).val(arr[index]).trigger('change');
	});

	try { //设置数值颜色显示
		$jqs.each(function(index, dom) {
			let inValue = dom.value;
			let orValue = $(dom).parent().find('div.input-group-prepend span').text();
			orValue = Number(orValue);
			if (inValue == orValue) {
				dom.style.color = 'black';
			} else if (inValue > orValue) {
				dom.style.color = 'red';
			} else {
				dom.style.color = 'blue';
			}
		});
	} catch (e) {
		console.log(e);
	}
}

function showImageSrcInCanvas(url) {
	var img = new Image();

	img.crossOrigin = "anonymous";
	img.src = url;
	//console.log('showImageSrcInCanvas.........', url);				
	return new Promise((resolve, reject) => {
		img.onload = function() {
			console.log('showImageSrcInCanvas onload.........', url);

			let $canvas = document.querySelector("#show");
			let $canvasBox = document.querySelector("#showBox");

			let context = $canvas.getContext("2d");
			let ctx = $canvasBox.getContext("2d");

			context.clearRect(0, 0, $canvas.width, $canvas.height);

			$canvas.setAttribute("width", this.width + "px");
			$canvas.setAttribute("height", this.height + "px");

			$canvasBox.setAttribute("width", this.width + "px");
			$canvasBox.setAttribute("height", this.height + "px");

			context.drawImage(this, 0, 0, this.width, this.height);
			ctx.drawImage(this, 0, 0, this.width, this.height);
			resolve($canvas.toDataURL());
		};
		img.onerror = (e) => {
			console.log('error in showImageSrcInCanvas', e);
			reject(e);
		};
	});
}
